package com.smart.gaorenhui.task;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletionService;

/**
 * @author Administrator
 */

@Log4j2
public class MyHandler {
    private static final String xApiAppid = "grh4ce19ca8fcd150a4_android";
    private static final String xApiToken = "cc55a8683e440aab7541075fc11e0439";
    private static final String xApiUid = "ZTM64B8CCD2DB1FF";
    private static final String xApiImei = "863342026409005";


    private static final String PLLB1 = "1693503066";
    private static final String PLLB2 = "479be6d324d61462bc455391f3c861aa69c3fc07";


    private static final String PLXQ1 = "1693493830";
    private static final String PLXQ2 = "aa6f63768c0556bc5b867169f5c72e1a30403c2b";

    private static final String ASK1 = "1693495663";
    private static final String ASK2 = "6f4e722c5d2e6769b44f08bd2a2c17407e68b8b2";

    private static final String U1 = "1693327572";
    private static final String U2 = "6497d12ec9b1fe363e75b94dda094bfcde46ebb0";
    //评论页 40
    private static final int PL_PAGE=40;

    //问答页面 1400
    private static final int ASK_PAGE=40 ;

    //多线层分页
    private static final int pageSize=100;




    public    void run() {
        ArrayList<MyExcleResult> rsList = new ArrayList<>();
        getPingLunList(rsList);
        log.warn("---------------------------评论采集完毕");
        getAskList(rsList);
        log.warn("---------------------------问答用户采集完毕");
        dxc(rsList);
        log.warn("---------------------------多线程执行完毕");
        toExcle(rsList);
        log.warn("Excle 写入完毕");
    }


    public static void dxc(ArrayList<MyExcleResult> rsList) {
        try {

            //存在写入数据 进行数据入库
            CompletionService<Integer> completionService = ThreadUtil.newCompletionService();
            List<List<MyExcleResult>> partition = ListUtil.partition(rsList, pageSize);
            int size = partition.size();
            for (int i = 0; i < size; i++) {
                int finalI = i;
                completionService.submit(() -> {
                    List<MyExcleResult> myExcleResults = partition.get(finalI);
                    myExcleResults.forEach(MyHandler::getUserInfo);
                    return finalI;
                });
            }

            for (int i = 0; i <size ; i++) {
                Integer xc = completionService.take().get();
                log.error("第{}线程执行完毕" ,xc);
            }


        } catch (Exception e) {
            e.printStackTrace();
            log.warn("多线程拆分错误" + e.getMessage());
        }
    }


    public static void toExcle(ArrayList<MyExcleResult> rsList) {
        String rq = DateUtil.format(new Date(), "yy-MM-dd-hh-mm");
        String fileName = "d:/".concat(rq).concat(".xlsx");
        BigExcelWriter bigWriter = ExcelUtil.getBigWriter(fileName);
        bigWriter.write(rsList, true);

        bigWriter.close();
    }


    public static void getPingLunList(ArrayList<MyExcleResult> rsList) {
        for (int i = 1; i <= PL_PAGE; i++) {
            String url = " http://yaf.gaoren.net/Divine/Orders/orderShareList?p="+i+"&app=gaorenhui&v=7.39&channel=qiniu";
            try {
                HttpResponse result = HttpUtil.createRequest(Method.GET, url)
                        .header("x-api-appid", xApiAppid)
                        .header("x-api-nonce", PLLB1)
                        .header("X-api-sign", PLLB2)
                        .header("x-api-token", xApiToken)
                        .header("x-api-uid", xApiUid)
                        .header("x-api-imei", xApiImei)
                        .execute();
                JSONObject jsonObject = JSONObject.parseObject(result.body());
                if (jsonObject.getString("errcode").equals("200")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray list = data.getJSONArray("list");
                    list.forEach(x -> {
                        JSONObject mx = JSONObject.parseObject(JSONObject.toJSONString(x));
                        MyExcleResult myExcleResult = getPingLunDetail(mx.getString("DOID"));
                        Opt.ofNullable(myExcleResult).ifPresent(rsList::add);
                    });
                    log.warn("问答列表---第 {} 页的列表页抓取成功", i);
                } else {
                    log.warn("问答列表---第:{}页摘取失败 结果非200 {}", url, result.body());
                }
            } catch (Exception exception) {
                log.warn("URL:{} 抓取失败：{}", url, exception.getMessage());
            }
        }

    }


    public static MyExcleResult getPingLunDetail(String plId) {
        String url = "http://yaf.gaoren.net/Divine/Orders/orderShare?doid=" + plId + "&app=gaorenhui&v=7.39&channel=qiniu HTTP/1.1";
        try {
            HttpResponse result = HttpUtil.createRequest(Method.GET, url)
                    .header("x-api-appid", xApiAppid)
                    .header("x-api-nonce", PLXQ1)
                    .header("X-api-sign", PLXQ2)
                    .header("x-api-token", xApiToken)
                    .header("x-api-uid", xApiUid)
                    .header("x-api-imei", xApiImei)
                    .execute();

            JSONObject jsonObject = JSONObject.parseObject(result.body());
            if ("200".equals(jsonObject.getString("errcode"))) {
                JSONObject data = jsonObject.getJSONObject("data");
                MyExcleResult myExcleResult = new MyExcleResult();
                myExcleResult.setBanKuai("评论").setUserId(data.getString("UID")).setCreateTime(data.getString("CreateTime"));
                return myExcleResult;
            } else {
                log.warn("详情页{} 结果非200 {}", url, jsonObject);
            }
        } catch (Exception exception) {
            log.warn("URL:{} 抓取失败：{}", url, exception.getMessage());
        }


        return null;
    }


    public static void getAskList(ArrayList<MyExcleResult> rsList) {

            for (int page = 1; page < ASK_PAGE; page++) {
                getAskDetail( page, rsList);

        }
    }


    public static void getAskDetail(int page, ArrayList<MyExcleResult> rsList) {
        String url = "http://yaf.gaoren.net/Divine/Forum/tieList?p=" + page + "&dpid=1&app=gaorenhui&v=7.39&channel=qiniu";
        try {
            HttpResponse result = HttpUtil.createRequest(Method.GET, url)
                    .header("x-api-appid", xApiAppid)
                    .header("x-api-nonce", ASK1)
                    .header("X-api-sign", ASK2)
                    .header("x-api-token", xApiToken)
                    .header("x-api-uid", xApiUid)
                    .header("x-api-imei", xApiImei)
                    .execute();
            String body = result.body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getString("errcode").equals("200")) {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray list = data.getJSONArray("list");
                list.forEach(x -> {
                    JSONObject mx = JSONObject.parseObject(JSONObject.toJSONString(x));
                    String uid = mx.getString("UID");
                    String createTime = mx.getString("CreateTime");
                    MyExcleResult myExcleResult = new MyExcleResult();
                    myExcleResult.setBanKuai("问答").setUserId(uid).setCreateTime(createTime);
                    rsList.add(myExcleResult);
                });
                log.warn("问答列表---第{}页 抓取成功", page);
            } else {
                log.warn("问答列表---第{}页 抓取失败  错误信息:{}", page,body);


            }
        } catch (Exception exception) {
            log.warn("问答列表---第{}页 抓取失败  错误信息:{}", page,exception.getMessage());
        }

    }


    public static void getUserInfo(MyExcleResult myExcleResult) {
        String url = "http://yaf.gaoren.net/Divine/Users/userInfo?app=gaorenhui&v=7.39&channel=qiniu";
        try {
            HttpResponse result = HttpUtil.createRequest(Method.GET, url)
                    .header("x-api-appid", xApiAppid)
                    .header("x-api-nonce", U1)
                    .header("X-api-sign", U2)
                    .header("x-api-token", xApiToken)
                    .header("x-api-uid", myExcleResult.getUserId())
                    .header("x-api-imei", xApiImei)
                    .execute();
            JSONObject jsonObject = JSONObject.parseObject(result.body());
            if ("200".equals(jsonObject.getString("errcode"))) {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray resellerCaseList = data.getJSONArray("ResellerCaseList");
                JSONObject ShareData = data.getJSONObject("ShareData");


                myExcleResult.setTel(data.getString("CellPhone"))
                        .setSex(data.getString("Sex"))
                        .setNickName(data.getString("NickName"))
                        .setCity(data.getString("City"))
                        .setArea(data.getString("Area"))
                        .setBirthday(data.getString("Birthday"))
                        .setSource(data.getString("Source"))
                        .setRank(data.getString("RankName"))
                        .setUserType(data.getString("Utype") )
                        .setOrderNum(data.getString("OrderNum"))
                        .setFee(data.getString("Balance"));

                if (!ShareData.isEmpty()) {
                    myExcleResult.setYxrId(ShareData.getString("id")) ;
                }



                Opt.ofEmptyAble(resellerCaseList).ifPresent(x->{
                    JSONObject from = JSONObject.from(x.get(0));
                    myExcleResult.setXfRmb(from.getString("Amount")).setXfTime(from.getString("time"));
                }) ;

                log.warn("用户信息--------采集成功:{}", myExcleResult.getUserId());
            } else {
                log.warn("用户信息--------第{}采集失败:{}",  url, result.body());
            }
        } catch (Exception exception) {
            log.warn("用户信息--------第{}采集失败:{}",  url, exception.getMessage());
        }


    }

}
